package com.jigsawapp.movies.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jigsawapp.movies.AppContext;
import com.jigsawapp.movies.R;
import com.jigsawapp.movies.api.AsyncHttpHelp;
import com.jigsawapp.movies.api.MoviesApi;
import com.jigsawapp.movies.bean.Session;
import com.jigsawapp.movies.common.Contanst;
import com.jigsawapp.movies.common.CyptoUtils;
import com.jigsawapp.movies.common.StringUtils;
import com.jigsawapp.movies.common.UIHelper;
import com.jigsawapp.movies.util.JsonUtils;
import com.kymjs.rxvolley.client.HttpCallback;


import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements View.OnClickListener,
        TextView.OnEditorActionListener, TextWatcher {

    private AppContext mContext;

    @InjectView(R.id.et_account)
    AutoCompleteTextView etAccount;

    @InjectView(R.id.et_password)
    EditText etPasword;

    @InjectView(R.id.bt_login)
    Button btLogin;

    @InjectView(R.id.text_reg)
    TextView tvRegister;

    private ProgressDialog mLoginProgressDialog;
    private InputMethodManager inputMethodManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        initView();
    }

    private void initView() {
        btLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        //添加文本变化监听
        etAccount.addTextChangedListener(this);
        etPasword.addTextChangedListener(this);
        etPasword.setOnEditorActionListener(this);
        Log.d("tag1", AppContext.getInstance().getProperty(Contanst.ACCOUNT_EMAIL));

        String account = CyptoUtils.decode(Contanst.ACCOUNT_EMAIL, AppContext.getInstance()
                .getProperty(Contanst.ACCOUNT_EMAIL));
        etAccount.setText(account);

        String pwd = CyptoUtils.decode(Contanst.ACCOUNT_PWD, AppContext.getInstance()
                .getProperty(Contanst.ACCOUNT_PWD));

        etPasword.setText(pwd);
    }

    @Override
    @OnClick({R.id.bt_login, R.id.text_reg})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                inputMethodManager.hideSoftInputFromWindow(etPasword.getWindowToken(), 0);
                checkLogin();
                break;
            case R.id.text_reg:
                mContext = (AppContext) getApplicationContext();
                Intent intent = new Intent(mContext, RegisterActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }

    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        //输入法里点击完成就会去登陆
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            checkLogin();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etPasword.getWindowToken(), 0);
            return true;
        }
        return false;
    }

    private void checkLogin() {
        String email = etAccount.getText().toString();
        String password = etPasword.getText().toString();

        if (StringUtils.isEmpty(email)) {
            UIHelper.toastMessage(this, "请输入邮箱");
            return;
        }
        if (!StringUtils.isEmail(email)) {
            UIHelper.toastMessage(this, "无效邮箱地址");
            return;
        }

        if (StringUtils.isEmpty(password)) {
            UIHelper.toastMessage(this, "请输入密码");
            return;
        }

        AppContext.getInstance().saveAccountInfo(CyptoUtils.encode(Contanst.ACCOUNT_EMAIL, email),
                CyptoUtils.encode(Contanst.ACCOUNT_PWD, password));
        
        login(email, password);
    }

    private void login(String email, String password) {
        if (mLoginProgressDialog == null) {
            mLoginProgressDialog = new ProgressDialog(this);
            mLoginProgressDialog.setCancelable(true);
            mLoginProgressDialog.setCanceledOnTouchOutside(false);
            mLoginProgressDialog.setMessage("正在登陆");
        }
        MoviesApi.login(email, password, new HttpCallback() {
            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);
                Session session = JsonUtils.toBean(Session.class, t);
                //保存用户信息
                if(session != null) {
                    AppContext.getInstance().saveLoginInfo(session);
                }
                //保存token到本地
                if (session.getPrivate_token() != null) {
                    String token = CyptoUtils.encode(AsyncHttpHelp.MOVIES_PRIVATE_TOKEN, session.getPrivate_token());
                    AppContext.getInstance().setProperty(AsyncHttpHelp.PRIVATE_TOKEN, token);
                }
                setResult(RESULT_OK);
                //TODO:差一个广播
                finish();

            }


            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                Log.d("tag", t);
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                if (errorNo == 401) {
                    UIHelper.toastMessage(LoginActivity.this, "用户未登录 或 密码错误");
                } else {
                    UIHelper.toastMessage(LoginActivity.this, "登录失败");
                }
            }
            @Override
            public void onPreStart() {
                super.onPreStart();
                if (mLoginProgressDialog != null) {
                    mLoginProgressDialog.show();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (mLoginProgressDialog != null && mLoginProgressDialog.isShowing()) {
                    mLoginProgressDialog.dismiss();
                }
            }
        });

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        //密码和账户为空俺就不让点

        String account = etAccount.getText().toString();
        String pwd = etPasword.getText().toString();
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
            btLogin.setEnabled(false);
        } else {
            btLogin.setEnabled(true);
        }
    }
}
